<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator函数的this</title>
</head>
<body>
    <h1>Generator函数的this</h1>
    <h2>Generator函数总是返回一个遍历器，ES6规定这个遍历器是Generator函数的实例</h2>

    <script>
        // Generator函数的this问题
        function* gen() {
            this.a = 1;
            yield this.b = 2;
            yield this.c = 3;
        }

        // 直接调用
        const g = gen();
        console.log(g.next()); // { value: 2, done: false }
        console.log(g.a); // undefined

        // 使用new操作符
        function* Gen() {
            this.a = 1;
            yield this.b = 2;
            yield this.c = 3;
        }
        Gen.prototype.hello = function() {
            return 'hi!';
        };

        let g2 = new Gen();
        console.log(g2.hello()); // 'hi!'

        // 使用call方法绑定this
        function* F() {
            this.x = 1;
            yield this.y = 2;
            yield this.z = 3;
        }

        const obj = {};
        const f = F.call(obj);

        f.next();  // {value: 2, done: false}
        f.next();  // {value: 3, done: false}
        f.next();  // {value: undefined, done: true}

        console.log(obj.x); // 1
        console.log(obj.y); // 2
        console.log(obj.z); // 3
    </script>
</body>
</html> 